var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasStyle = window.getComputedStyle(canvas,null);
var size = 4
canvas.width = parseInt(canvasStyle["width"]);
canvas.height = parseInt(canvasStyle["width"]);
var blocksize = canvas.width/size;
var blocks = [];
function newgame (){
    blocks=[];
    for(var i = 0;i < size * size;i++){ 
        blocks.push(true)
    }
    for(var i= 0;i < size + 1;i++){
        blocks[parseInt(Math.random()*blocks.length)] = false;
    }
    draw()

}
function draw(){
    var count = 0
    for(var i = 0;i<blocks.length;i++){
        block = blocks[i]
        if(block){
            ctx.fillStyle = "white"
            count++
        }
        else{
            ctx.fillStyle = "black"
        }
        ctx.beginPath()
        ctx.arc((i % size)*blocksize + blocksize /2,parseInt(i/size)*blocksize + blocksize/2,blocksize/2,0,Math.PI*2,false)
        ctx.stroke()
        ctx.fill()


    }
    if(count <=2){
        setTimeout(function(){
            alert("游戏胜利")
            newgame()
        },1000)
    }
}
canvas.addEventListener("click",function(evt){
    var cRect = canvas.getBoundingClientRect()
    var canvasX = Math.round(evt.clientX = cRect.left)
    var canvasY = Math.round(evt.clientY = cRect.top)
    var x = parseInt(canvasX / blocksize)
    var y = parseInt(canvasY / blocksize)
    var origin = y * size + x

    blocks[origin] = !blocks[origin]
    blocks[origin - size] = !blocks[origin - size]
    blocks[origin + size] = !blocks[origin + size]
    if(origin % size == size-1){
        blocks[origin-1] = !blocks[origin-1]
    }
    else if(origin % size ==0){
        blocks[origin + 1] = !blocks[origin + 1]
    }
    else{
        blocks[origin + 1] = !blocks[origin - 1]
        blocks[origin + 1] = !blocks[origin + 1]
    }
    block = blocks.slice(0,size*size)
    draw()
})
newgame()